//DATA INPUT PAGE================================================================================================
$(document).ready(function() {
    load_accordion();
    adjust_menu_itens();
//    load_time_picker_anim();
//    load_time_picker_triggers();
});
function load_accordion(){
    $( "#courses_accordion" ).accordion({
        collapsible: true,
        active: false,
        beforeActivate: function( event, ui ) {
            if(ui.newHeader.hasClass("editing")) 
                event.preventDefault();
        },
        activate: function(event, ui){
            if(ui.newHeader.length){
                $("html, body").animate({
                    scrollTop: ($(ui.newHeader).offset().top)
                 }, 1000);
            }
        }
    });
}
function adjust_menu_itens(){
    //dynamic css for menu itens
    var number_of_buttons = 0;
    $("#menu ul a").each(function(){
        number_of_buttons++;
    });
    
    if(number_of_buttons==8){ 
        $("#menu a").css("padding","0px 20px 0px 15px");
    }
}

function save_institution(formId){
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/save_institution",
            type: 'POST',
            data: $('#'+formId).serializeArray(),
            success: function(value){
                    session_expired_test(value);
                    $("#institution").html(value);
                    $("#new_course").show();
                    }
    });
    return false;
}
function save_new_course(formId){
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/save_course",
            type: 'POST',
            data: $('#'+formId).serializeArray(),
            success: function(value){
                    session_expired_test(value);
                    $("#courses_accordion").prepend(value);
                    $( "#courses_accordion" ).accordion("destroy");
                    load_accordion();
                }
    });
    return false;
}
function edit_course(form_id){
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_course",
            type: 'POST',
            data: $('#'+form_id).serializeArray(),
            success: function(value){
                try{
                   var json = JSON.parse(value);
                   if(json.redirect == true){
                       alert("Sessão Expirada!");
                       window.location.reload();
                   }else{
                       $("#course"+json.course_id+"_title_div").html(json.title);
                       $("#course"+json.course_id+"_content_div").html(json.content);
                       $('.course_display_element').remove();
                       $("#course"+json.course_id+"_title_div").effect("shake", { times:5 }, 1000);
                   }
                }catch(e){
                    alert("Ocorreu um erro");
                }
             }
    });
    return false;
}
function remove_course(course_id){
    if (confirm("Realmente deseja remover esta matéria e todas as suas turmas?")==true){
        $.ajax({
                url: URL_ROOT+"action/grademagica/remove_course",
                type: 'POST',
                data: "course_id="+course_id,
                success: function(value){
                    session_expired_test(value);
                    if(value=="ok"){
                       $( "#courses_accordion" ).accordion({
                            collapsible: true,
                            active:false
                        });
                       $("#course"+course_id+"_title_div").fadeOut(400, function(){
                           $("#course"+course_id+"_title_div").remove();
                           $("#course"+course_id+"_content_div").remove();
                           $( "#courses_accordion" ).accordion("destroy");
                           load_accordion();
                       });
                    }
                 }
        });
     }
}
function save_class(formId){
    if(!validate_form_hours_format(formId)) return false;
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/save_class",
            type: 'POST',
            data: $('#'+formId).serializeArray(),
            success: function(value){
                session_expired_test(value);
                $("#"+formId).parent().parent().find(".saved_classes").prepend(value);
                }
    });
    $('#'+formId)[0].reset();
    return false;
}
function cancel_class_edit(button_id){
    var form_id = $("#"+button_id).parents("form:first").attr("id");
    $.ajax({
            url: URL_ROOT+"action/grademagica/load_class",
            type: 'POST',
            data: $('#'+form_id).serializeArray(),
            success: function(value){
                session_expired_test(value);
                $("#"+form_id).fadeOut(500, function(){
                    $("#"+form_id).parent().replaceWith(value);
                });
                }
    });
}
function edit_class(form_id){
    var valid_hours = validate_form_hours_format(form_id);
    if(!valid_hours){
        alert("Horário em formato não aceito");
        return false;
    }
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_class",
            type: 'POST',
            data: $('#'+form_id).serializeArray(),
            success: function(value){
                session_expired_test(value);
                $("#"+form_id).parent().replaceWith(value);
                }
    });
    return false;
}
function remove_class(class_id, class_div_id){
    if(confirm("Deseja remover esta turma e todos os seus horários?")===true){
        $.ajax({
                url: URL_ROOT+"action/grademagica/remove_class",
                type: 'POST',
                data: "class_id="+class_id,
                success: function(message){
                    session_expired_test(message);
                    if(message=="ok"){
                        $("#"+class_div_id).fadeOut(500, function(){
                            $("#"+class_div_id).remove();
                        });
                    }
                }
        });
    }
    return false;
}
function load_edit_institution_interface(institution_id){
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_institution_interface",
            type: 'POST',
            data: 'institution_id='+institution_id,
            success: function(value){
                    $("#institution").html(value);
                    }
    });
    return false;
}
function load_edit_course_interface(course_id){
    $("#course"+course_id+"_title_div").addClass("editing");
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_course_interface",
            type: 'POST',
            data: "course_id="+course_id,
            success: function(message){
                    session_expired_test(message);
                    var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                    var inner_div = $(document.createElement('div'));
                    inner_div.addClass("course_display_inner");
                    inner_div.addClass("course_display_element");
                    inner_div.html(message);

                    var close = $(document.createElement('button'));
                    close.html("Fechar");
                    close.click(function(){
                        $('.course_display_element').remove();
                        $("#course"+course_id+"_title_div").removeClass("editing");
                    });
                    close.css({"font-weight":"bold", "width":"100%"});
                    inner_div.append(close);

                    var pop = $(document.createElement('div'));
                    pop.attr('id',rand_id);
                    pop.addClass("course_display");
                    pop.addClass("course_display_element");
                    pop.css({"zIndex":"1002" , "top": ($(document).scrollTop()+100)+"px"});
//                    pop.css({"zIndex":"1002" , "top": (parseInt((100*$(document).scrollTop())/$("body").height())).toString()+"%"});
                    pop.append(inner_div);

                    var fade = $(document.createElement('div'));
                    fade.css({"zIndex":"1001"});
                    fade.attr('class','overlay_backgroud');
                    fade.addClass("course_display_element");

                    $(document.body).append(pop);
                    $(document.body).append(fade);
                    $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
}
function load_edit_class_interface(class_id, class_div_id){
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_class_interface",
            type: 'POST',
            data: "class_id="+class_id.toString(),
            success: function(message){
                var class_div = $("#"+class_div_id);
                var accordion_content = class_div.parents(".accordion_element_content:first");
                session_expired_test(message);
                class_div.html(message);
                
                //auto scrolls to make the class_div COMPLETELY visible
                accordion_content.animate(
                    {scrollTop: (class_div.offset().top - accordion_content.offset().top +accordion_content.scrollTop())}
                ,1000);
                
                load_time_picker_anim();
                load_time_picker_triggers();
                }
    });
}

//@return true if valid; false otherwise
function validate_time_string(string){
    if(/^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(string))
        return true;
    else return false;
}
//@return true for valid; false otherwise
function validate_textfield_hours_format(textfield){
    var value = textfield.val();
    if(value==="") return false;
    else if(validate_time_string(value)){
           textfield.css("backgroundColor","#FFF");
           textfield.removeClass("format_invalid");
           return true;
        }else {
             textfield.css("backgroundColor","#F99");
             textfield.addClass("format_invalid");
             return false;
         }
}

//@return true for valid; false otherwise
function validate_textfield_hour_PAIR(textfield){
       var time_end_obj;
       var time_start_obj;
       if(textfield.hasClass("class_end")){
           time_end_obj = textfield;
           time_start_obj = textfield.parent().find(".class_start");
       }else if(textfield.hasClass("class_start")){
           time_start_obj = textfield;
           time_end_obj = textfield.parent().find(".class_end");
       }
       if(!validate_textfield_hours_format(time_end_obj) || !validate_textfield_hours_format(time_start_obj)){
           return false;
       }else
           try{
               var time_end = new Date("01/01/2001 "+time_end_obj.val());
               var time_start = new Date("01/01/2001 "+time_start_obj.val());

               if(time_start >= time_end){
                   $(this).css("backgroundColor","#F99");
                   time_start_obj.css("backgroundColor","#F99");
                   $(this).addClass("time_invalid");
                   time_start_obj.addClass("time_invalid");
                   return false;
               } else{
                   if(!time_start_obj.hasClass("format_invalid")){
                       time_start_obj.css("backgroundColor","#FFF");
                       time_start_obj.removeClass("time_invalid");
                   }
                   if(!$(this).hasClass("format_invalid")){
                       $(this).css("backgroundColor","#FFF");
                       $(this).removeClass("time_invalid");
                   }
                   return true;
               }
           }catch(e){
               $(this).css("backgroundColor","#F99");
               $(this).addClass("time_invalid");
               time_start_obj.css("backgroundColor","#F99");
               time_start_obj.addClass("time_invalid");
               return false;
           }
}
function validate_form_hours_format(form_id){
    var has_invalid = false;
    //valida formato dos horarios; par a par (class_time = classe do container do par)
    $("#"+form_id+" .class_time").each(function(){
        //valida ordem e formatos
       var textfield = $(this).find(".time:first");
       if(!validate_textfield_hour_PAIR(textfield)){
           has_invalid = true;
       }
    });
    
    if(has_invalid) return false;
    else return true;
}


//GENERATE GRID PAGE================================================================================================
function generate_grids(grid_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_grid",
            type: 'POST',
            data: "grid_id="+grid_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                inner_div.addClass("grid_display_inner");
                inner_div.addClass("grid_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.grid_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("grid_display");
                pop.addClass("grid_display_element");
                pop.css({"zIndex":"1002"});
                pop.append(inner_div);

                var fade = $(document.createElement('div'));
                fade.css({"zIndex":"1001"});
                fade.attr('class','overlay_backgroud');
                fade.addClass("grid_display_element");

                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
    return false;
}
function overlay_grid(grid_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_grid",
            type: 'POST',
            data: "grid_id="+grid_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                inner_div.addClass("grid_display_inner");
                inner_div.addClass("grid_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.grid_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("grid_display");
                pop.addClass("grid_display_element");
                pop.css({"zIndex":"1002"});
                pop.append(inner_div);

                var fade = $(document.createElement('div'));
                fade.css({"zIndex":"1001"});
                fade.attr('class','overlay_backgroud');
                fade.addClass("grid_display_element");

                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
    return false;
}

function visualize_course(course_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_course",
            type: 'POST',
            data: "course_id="+course_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                var highest_index = get_highest_zIndex();
                
                inner_div.addClass("course_display_inner");
                inner_div.addClass("course_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.course_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("course_display");
                pop.addClass("course_display_element");
                pop.append(inner_div);
                pop.css({"zIndex":(highest_index+2).toString()});
                
                var fade = $(document.createElement('div'));
                fade.attr('class','overlay_backgroud');
                fade.addClass("course_display_element");
                fade.css({"zIndex":(highest_index+1).toString()});
                
                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
}
function visualize_class(class_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_class",
            type: 'POST',
            data: "class_id="+class_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                var highest_index = get_highest_zIndex();
                
                inner_div.addClass("class_display_inner");
                inner_div.addClass("class_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.class_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("class_display");
                pop.addClass("class_display_element");
                pop.append(inner_div);
                pop.css({"zIndex":(highest_index+2).toString()});
                
                var fade = $(document.createElement('div'));
                fade.attr('class','overlay_backgroud');
                fade.addClass("class_display_element");
                fade.css({"zIndex":(highest_index+1).toString()});
                
                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
}

//OTHERS

